package com.lagou.client;

import com.lagou.client.handler.UserClientHandler;
import com.lagou.pojo.Request;
import com.lagou.service.impl.JSONSerializer;
import com.lagou.util.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class RPCConsumer {

    // 1. 创建一个线程池对象 -- 它要处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // 2. 声明一个自定义事件处理器
    private static UserClientHandler userClientHandler;

    // 用于记录每个服务端的UserClientHandler， 而不是所有的服务端公用一个UserClientHandler
    public static Map<String, UserClientHandler> userClientHandlerMap = new HashMap<>();


    // 3. 编写方法，初始化客户端（创建连接池、bootstrap、设置bootstrap、连接服务器）
    public static void initClient(String serverAddress) {
        if (StringUtils.isBlank(serverAddress)) {
            return;
        }
        String[] addressArr = serverAddress.split("_");
        if (addressArr.length < 2) {
            return;
        }
        // 1. 初始化UserClientHandler
        userClientHandler = new UserClientHandler();
        // 2. 创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 3. 创建客户端的引导类对象
        Bootstrap bootstrap = new Bootstrap();
        // 4. 配置启动引导类
        bootstrap.group(group)
                // 设置通道为NIO
                .channel(NioSocketChannel.class)
                // 设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5)
                // 监听channel，并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取channel pipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 设置编码
                        pipeline.addLast(new RpcEncoder(Request.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        // 添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        try {
            // 5. 连接服务端
            bootstrap.connect(addressArr[0], Integer.parseInt(addressArr[1])).sync();
        } catch (Exception ignored) {
        }
    }

    public static Object createProxy(final Class<?> serviceClass, final String serverAddress) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader()
                , new Class[]{serviceClass}, (proxy, method, args) -> {
                    // 1. 初始化客户端client
                    if (userClientHandlerMap.get(serverAddress) == null) {
                        initClient(serverAddress);
                    }

                    Request request = new Request();
                    request.setClassName(method.getDeclaringClass().getName());
                    request.setMethodName(method.getName());
                    request.setParameterType(method.getParameterTypes());
                    request.setParameters(args);

                    // 2. getUserClientHandler 设置参数
//                    userClientHandlerMap.get(serverAddress).setParam(request);
                    userClientHandler.setParam(request);

                    // 3. 使用线程池，开启一个线程处理call()，写操作并返回结果
                    Object result = executorService.submit(userClientHandler).get();

                    // 4. return结果
                    return result;
                });
    }


}
